package com.crazydream.wechat.security.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.crazydream.wechat.system.model.Role;
import com.crazydream.wechat.system.model.User;
import com.crazydream.wechat.system.service.UserService;

public class UserDetailsServiceImpl implements UserDetailsService {
	
	private UserService userService;
	
	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException {

		// 使用User服务类查询数据用户是否存在,如不存在或密码错误则抛出对应的异常
		List<User> users = this.userService.findByUserName(username);
		if (null == users || users.isEmpty())
			throw new UsernameNotFoundException("用户/密码错误,请重新输入!");

		User user = users.get(0);
		List<Role> roles = user.getRoleList();
		if (null == roles || roles.isEmpty())
			throw new UsernameNotFoundException("权限不足!");
		// 把权限赋值给当前对象
		Collection<GrantedAuthority> gaRoles = new ArrayList<GrantedAuthority>();
		for (Role role : roles) {
			gaRoles.add(new SimpleGrantedAuthority(role.getName()));
		}
		user.setAuthorities(gaRoles);
		return user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}	
	
}
